package com.xywei.config.security;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

//@Component("securityCustomAccessDecisionManager")
public class SecurityCustomAccessDecisionManager implements AccessDecisionManager {

	/**
	 * authentication: 认证的主体<br>
	 * object：访问的资源<br>
	 * configAttributes: 需要的权限
	 */
	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {

		if (configAttributes == null) {
			return;
		}
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();
		while (iterator.hasNext()) {
			ConfigAttribute configAttribute = (ConfigAttribute) iterator.next();
			String needAuthority = configAttribute.getAttribute();
			Collection<? extends GrantedAuthority> authenticationAuthorities = authentication.getAuthorities();
			if (authenticationAuthorities != null) {
				for (GrantedAuthority grantedAuthority : authenticationAuthorities) {
					String authorityName = grantedAuthority.getAuthority();
					if (needAuthority.equals(authorityName)) {
						return;
					}
				}
			}
		}

		throw new AccessDeniedException("对不起，你没有权限！");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
